package com.example.growthmuseum.postgoods;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.growthmuseum.AppController;
import com.example.growthmuseum.flow.FlowActivity;
import com.example.growthmuseum.R;
import com.example.growthmuseum.ServiceFactory;
import com.example.growthmuseum.data.model.Goods;
import com.example.growthmuseum.data.model.Result;
import com.example.growthmuseum.data.model.User;
import com.example.growthmuseum.service.GoodsService;
import com.example.growthmuseum.service.UserService;
import com.orhanobut.logger.Logger;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Roman on 2016/10/29.
 */
public class PostGoodsNextActivity extends AppCompatActivity {

    private EditText nameEdit;

    private EditText mobileEdit;

    private EditText addressEdit;

    private Button postBtn;

    private Goods goods;

    private GoodsService goodsService;

    private UserService userService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_goods_next);

        initViews();

        this.goodsService = ServiceFactory
                .createRetrofitService(GoodsService.class,
                        ServiceFactory.BASE_URL);

        this.userService = ServiceFactory
                .createRetrofitService(UserService.class,
                        ServiceFactory.BASE_URL);
    }

    private void initViews() {
        String data = AppController.getInstance().getCache().getAsString("user");
        User cacheUser = JSON.parseObject(data, User.class);
        nameEdit = (EditText) findViewById(R.id.name_edit);
        if (cacheUser.getName() != null) {
            nameEdit.setText(cacheUser.getName());
        }
        mobileEdit = (EditText) findViewById(R.id.mobile_edit);
        if (cacheUser.getMobile() != null) {
            mobileEdit.setText(cacheUser.getMobile());
        }
        addressEdit = (EditText) findViewById(R.id.address_edit);
        if (cacheUser.getAddress() != null) {
            addressEdit.setText(cacheUser.getAddress());
        }
        postBtn = (Button) findViewById(R.id.post_btn);
        postBtn.setOnClickListener(v -> {
            if (nameEdit.getText().toString().trim().isEmpty()) {
                Toast.makeText(PostGoodsNextActivity.this,
                        getResources().getString(R.string.goods_name_not_null), Toast.LENGTH_SHORT).show();
            } else if (mobileEdit.getText().toString().trim().isEmpty()) {
                Toast.makeText(PostGoodsNextActivity.this,
                        getResources().getString(R.string.mobile_not_null), Toast.LENGTH_SHORT).show();
            } else if (addressEdit.getText().toString().trim().isEmpty()) {
                Toast.makeText(PostGoodsNextActivity.this,
                        getResources().getString(R.string.address_not_null), Toast.LENGTH_SHORT).show();
            } else {
                User user = JSON.parseObject(AppController.getInstance().getCache().getAsString("user"), User.class);
                goods = new Goods();
                goods.setGoodsPic("");
                goods.setGoodsInfo(PostGoodsNextActivity.this.getIntent().getStringExtra("goods_info"));
                goods.setGoodsName(PostGoodsNextActivity.this.getIntent().getStringExtra("goods_name"));
                goods.setGoodsStatus(0);
                goods.setDonate(0);
                goods.setUserId(user.getId());
                Toast.makeText(PostGoodsNextActivity.this, "loading", Toast.LENGTH_SHORT).show();
                goodsService.addGoods(goods)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<Result<Integer>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e(e, e.getMessage());

                            }

                            @Override
                            public void onNext(Result<Integer> result) {
                                if (result.getCode().equals(Result.SUCCESS)) {
                                    String data = AppController.getInstance()
                                            .getCache().getAsString("user");
                                    User user = JSON.parseObject(data, User.class);
                                    user.setName(nameEdit.getText().toString().trim());
                                    user.setMobile(mobileEdit.getText().toString().trim());
                                    user.setAddress(addressEdit.getText().toString().trim());
                                    updateUser(user);
                                } else {
                                    Toast.makeText(PostGoodsNextActivity.this,
                                            result.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

            }
        });
    }

    private void updateUser(User user) {
        Toast.makeText(PostGoodsNextActivity.this, "update", Toast.LENGTH_SHORT).show();
        userService.updateUser(user)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<Integer>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e, e.getMessage());

                    }

                    @Override
                    public void onNext(Result<Integer> result) {
                        if (result.getCode().equals(Result.SUCCESS)) {
                            AppController.getInstance().getCache().put("user",
                                    JSON.toJSONString(user));
                            Intent toFlow = new Intent(PostGoodsNextActivity.this,
                                    FlowActivity.class);
                            startActivity(toFlow);
                            finish();
                        } else {
                            Toast.makeText(PostGoodsNextActivity.this,
                                    result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


}
